import logging
import time

from src.android.adb.drive import ADB
from src.android.adb.element import Element

LOG = logging.getLogger()


class Control(object):
    def __init__(self):
        self.max_confirm_times = 4

    def _click_string(self, str1):
        element = Element()
        e1 = element.find_element_by_attrib('text', str1)
        if not e1:
            err_msg = 'not find element={}'.format(str1)
            LOG.error(err_msg)
            return 0, 0
        x, y = e1[0], e1[1]
        return x, y

    def click_string(self, str1):
        x_y_list = []
        for i in range(self.max_confirm_times):
            time.sleep(5)
            x, y = self._click_string(str1)
            x_y_list.append((x, y))
            if i != 0 and x + y != 0 and x_y_list[i] == x_y_list[i - 1]:
                LOG.info("'{}' coordinate is x,y={},{}".format(str1, x, y))
                ADB.tap(x, y)
                break
            elif i > 1:
                LOG.warning("'{}' coordinate changed, retry {} times".format(str1, i - 1))
        else:
            err_msg = "'{}' coordinate change {} times, coordinate={}".format(
                str1, self.max_confirm_times, x_y_list)
            LOG.error(err_msg)
            raise Exception(err_msg)

    def unlock_phone(self):
        ADB.unlock_phone()
